import axios from "axios";
// import local from '@/utils/local.js'
// 创建axios实例
const service = axios.create({
  baseURL: import.meta.env.VITE_APP_BASE_API,
  timeout: 12000,
});

// 请求拦截器
service.interceptors.request.use(
  (config) => {
    // config.headers.accesstoken = localStorage.getItem("accessToken") ?? "";
    return config;
  },
  function (err) {
    return Promise.reject(err);
  }
);

// 响应拦截器
service.interceptors.response.use(
  function (response) {
    if (response.data.code === 200) {
      return response.data;
    } else {
      if (response.data.code == 500) {
        // ElMessage.error('token过期,请重新登录')

        // local.remove('TokenKey') //清空token
        localStorage.setItem("accessToken", "");
        // router.push("/login");
        // window.parent.location.href = "#/login";
        return response;
      } else if (response.data.code == 3) {
        // ElMessage.error('系统错误，请稍候再试！')
        return response;
      } else if (response?.data.code) {
        // ElMessage.error(response.data?.message)
        return response;
      } else {
        return response;
      }
    }
  },
  function (err) {
    // console.log("err", err);
    let { message } = err;
    if (message === "Network Error") {
      message = "网络连接失败";
    } else if (message.includes("timeout")) {
      message = "网络超时";
    } else if (message.includes("Request failed with status code")) {
      // window.parent.location.href = "#/login";
      message = "请求失败";
    }
    // ElMessage.error(message)
    return Promise.reject(err); //超时不重新请求
  }
);

export default service;
